package com.qf.openapi.web.master.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Slf4j
@WebFilter("/*")
public class TimeFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("===================== TimeFilter init =====================");
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
        HttpServletRequest req = (HttpServletRequest) request;
        
        log.debug("=======>url={}", req.getRequestURI());
        
        String name;
        String[] value;
        List<String> valueList;
        HashMap<String, List<String>> stringListHashMap = new HashMap<>();;
        
        //把请求中的参数信息打印出来
        Map<String, String[]> parameterMap = req.getParameterMap();
        ArrayList<HashMap<String, List<String>>> hashMaps = new ArrayList<>();
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            name = stringEntry.getKey();
            value = stringEntry.getValue();
            valueList = Arrays.asList(value);
            stringListHashMap.put(name, valueList);
            hashMaps.add(stringListHashMap);
        }
        
        log.debug("请求参数为：params={}", hashMaps);
    
        HashMap<String, String> headerMap = new HashMap<>();
        String headerName;
        String headerValue;
    
        //请求头信息打印
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()){
            headerName = headerNames.nextElement();
            headerValue = req.getHeader(headerName);
            headerMap.put(headerName, headerValue);
        }
        
        log.debug("请求头参数为：headers={}",headerMap);
    
    
        long start = System.currentTimeMillis();
        
        //放行当前请求
        chain.doFilter(request, response);
    
        long end = System.currentTimeMillis();
        
        log.debug("<=======url={},time={}", req.getRequestURI(), start - end);
    }
    
    @Override
    public void destroy() {
    
    }
}
